const mongoose = require('mongoose');
const jwt = require('jwt-simple')
const SECRET = 'AMC_MERCHANT_SECRET'   // secret key

const MerchantSchema = require('../schema/merchant.schema');

const MerchantModel = mongoose.model('Merchant', MerchantSchema);

function getMerchantById(id, callback) {
    MerchantModel.findById(id, function (err, doc) {
        if (err) {
            console.log(err);
            callback({status:false,data:{},message:'服务器异常'});
        } else {
            callback({status:true,data:doc,message:''});
        }
    });
}

function getMerchantList(callback) {
    MerchantModel.find(function (err, doc) {
        if (err) {
            console.log(err);
            callback({status:false,data:{},message:'服务器异常'});
        } else {
            callback({status:true,data:doc,message:''});
        }
    });
}

function insertMerchant(merchant, callback) {
    let m = new MerchantModel(
        {
            merchantName: merchant.name,
            password: merchant.password,
            address: merchant.address,
            headPic: merchant.headPic,
            idCardPic: merchant.idCardPic
        }
    );
    m.save(function (err, doc) {
        if (err) {
            console.log(err);
            callback({status:false,data:{},message:'服务器异常'});
        } else {
            callback({status:true,data:doc,message:''});
        }
    });
}

function deleteMerchantById(id, callback) {
    MerchantModel.remove({ _id: id }, function (err) {
        if (err) {
            console.log(err);
            callback({status:false,message:'服务器异常'});
        } else {
            callback({status:true,message:''});
        }
    });
}

function updateMerchant(merchant, callback) {
    MerchantModel.update(
        {
            _id: merchant._id
        },
        merchant,
        function (err, doc) {
            if (err) {
                console.log(err);
                callback({status:false,data:{},message:'服务器异常'});
            } else {
                callback({status:true,data:doc,message:''});
            }
        }
    );
}

function checkLoginInfo(merchantName, password, callback) {
    MerchantModel.findOne(
        {
            merchantName: merchantName,
            password: jwt.encode(password, SECRET)
        },
        function (err, doc) {
            if (err) {
                console.log(err);
                callback({status:false,data:{},message:'服务器异常'});
            } else {
                if(doc){
                    callback({status:true,data:doc,message:''});
                }else{
                    callback({status:false,data:{},message:'用户名或密码错误！'});
                }
               
            }
        });
}

module.exports = {
    getMerchantById: getMerchantById,
    getMerchantList: getMerchantList,
    insertMerchant: insertMerchant,
    deleteMerchantById: deleteMerchantById,
    updateMerchant: updateMerchant,
    checkLoginInfo: checkLoginInfo
}